package com.fzy.servlet;

import com.fzy.Dao.EmployeeDao;
import com.fzy.Dao.EmployeeDaoImpl;
import com.fzy.beansa.Employee;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/EditEmployeeServlet")
public class EditEmployeeServlet extends ViewBaseServlet {

    // 处理GET请求 - 显示编辑页面
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置请求编码
            request.setCharacterEncoding("UTF-8");

            // 获取员工ID参数
            String employeeId = request.getParameter("employeeid");
            System.out.println("employeeId: " + employeeId);
            EmployeeDao employeeDao = new EmployeeDaoImpl();
            Employee employee = employeeDao.SelectEmployee(employeeId);
            if (employee != null) {
                System.out.println("yes");
                request.setAttribute("employee", employee);
                //  调用模板方法
                processTemplate("editEmployee", request, response);
                return;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 处理POST请求 - 提交编辑表单
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置请求编码
            request.setCharacterEncoding("UTF-8");

            // 获取表单参数
            String employeeId = request.getParameter("employeeid");
            String employeeName = request.getParameter("employeename");
            double employeeSalary = Double.parseDouble(request.getParameter("employeesalary"));

            // 创建员工对象
            Employee employee = new Employee();
            employee.setEmployeeid(employeeId);
            employee.setEmployeename(employeeName);
            employee.setEmployeesalary(employeeSalary);

            // 更新员工信息
            EmployeeDao employeeDao = new EmployeeDaoImpl();
            int rs = employeeDao.UpdateEmployee(employee);

            if (rs > 0) {
                System.out.println("yes");
            }
            // 重定向到员工列表页面
            response.sendRedirect("GetAllEmployeeServlet");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "系统错误: " + e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }
}
